<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>
    <script src="./js/axios.js"></script>

</head>
<body>
<div id="app">

    <h1>聊天室</h1>
    <button @click="handleShow">打开/关闭聊天室</button>

    <hr>
    <Child v-if="show"></Child>
    <hr>

</div>
</body>

<script>
    Vue.component('Child', {
        template: `
          <div>
          <h3>聊天室</h3>
          <p v-for="item in chatList">{{ item.ctime }} {{ item.from_user }}说：{{ item.content }}</p>
          <hr>
          姓名： <input type="text" v-model="name">
          <input type="text" v-model="content">
          <button @click="handleSend">发送</button>
          </div>`,
        data() {
            return {
                t: null,
                chatList: [
                ],
                name: '',
                content: ''
            }

        },
        methods: {
            handleSend() {
                //发送ajax请求，到后端，
                axios.get(`http://127.0.0.1:8010/chat/send/?from_user=${this.name}&content=${this.content}`).then(res => {
                    if (res.data.code == 100) {
                        alert(this.data.msg)
                    } else {
                        alert(this.data.msg)
                    }
                })
            }
        },
        created() {
            // 创建定时器
            this.t = setInterval(() => {
                // 发送ajax请求
                axios.get('http://127.0.0.1:8010/chat/').then(res => {
                    // console.log(res.data.data.results)
                    this.chatList=res.data.data.results
                    console.log(this.chatList)
                })
            }, 3000)
        },
        beforeDestroy() {
            clearInterval(this.t) // 销毁定时器
            this.t = null
        }


    })

    var vm = new Vue({
        el: '#app',
        data: {
            show: true
        },
        methods: {
            handleShow() {
                this.show = !this.show
            }
        }

    })


</script>
</html>